#!/bin/bash

########################################
# This build script:
# 1. Navigates to karma-web directory and creates a shaded .war file.
# 2. Copies the .war snapshot and other .war files in external_webapps to the target folder.
# 3. Downloads apache tomcat.
# 4. Copies the war files to webapps folder.
# 5. Copies conf files to tomcat folder.
# 6. Navigates to the electron app folder and copies the tomcat folder to app/app directory.
# 7. Runs the release script there to build karma app for linux, windows and mac.
########################################
set -e

CURRENT=`pwd`
rm -rf ./target
mkdir target

cd ..
mvn clean install -Dmaven.test.skip=true
cd karma-web/

set +e
rm src/main/webapp/publish/CSV/*.csv
rm src/main/webapp/publish/AVRO/*.avro
rm src/main/webapp/publish/JSON/*.json
rm src/main/webapp/publish/KML/*.kml
rm src/main/webapp/publish/MDB/*.mdb
rm src/main/webapp/publish/R2RML/*.ttl
rm src/main/webapp/publish/R2RML/*.txt
rm src/main/webapp/publish/RDF/*.rdf
rm src/main/webapp/publish/RDF/*.ttl
rm src/main/webapp/publish/RDF/*.txt
rm src/main/webapp/publish/REPORT/*.md
set -e

mvn package -Pshaded
cp target/karma-web*.war $CURRENT/target/ROOT.war
cp external_webapps/* $CURRENT/target/

mv $CURRENT/target/cluster*.war $CURRENT/target/clusterService.war

cd $CURRENT/target

# download jre8
wget https://github.com/alseambusher/karma-app-deps/archive/master.zip
unzip master.zip
mv karma-app-deps-master/*.tar.gz .
rm -rf karma-app-deps-master master.zip
# download tomcat binary
wget https://dlcdn.apache.org/tomcat/tomcat-8/v8.5.72/bin/apache-tomcat-8.5.72.zip
unzip apache-tomcat-*.zip
rm apache-tomcat-*.zip
mv apache-tomcat* tomcat
rm -rf tomcat/webapps/*
mv *.war tomcat/webapps
chmod +x tomcat/bin/*.sh
cp $CURRENT/conf/* tomcat/conf/

rm -rf $CURRENT/desktop/app/tomcat
mv tomcat $CURRENT/desktop/app/

cd $CURRENT/desktop/app/tomcat/webapps
mkdir ROOT
mv ROOT.war ROOT/ROOT.zip
cd ROOT
unzip ROOT.zip
cd $CURRENT/desktop
npm install
npm run prerelease
cd app
tar -xzvf $CURRENT/target/jre*windows*.tar.gz
electron-packager . --platform=win32 --arch=x64 --icon=../resources/icons/karma.ico --overwrite
rm -rf jre*
tar -xzvf $CURRENT/target/jre*macosx*.tar.gz
electron-packager . --platform=darwin --arch=x64 --icon=../resources/icons/karma.icns --overwrite
rm -rf jre*
tar -xzvf $CURRENT/target/jre*linux*.tar.gz
electron-packager . --platform=linux --arch=x64 --icon=../resources/icons/karma.png --overwrite
rm -rf jre*

cp -rf Karma-darwin* $CURRENT/target/Karma-Mac
cp -rf Karma-linux* $CURRENT/target/Karma-Linux
cp -rf Karma-win* $CURRENT/target/Karma-Windows
set +e
rm -rf Karma-*

cd $CURRENT/target
rm *.tar.gz
set -e
#put our license
for build_folder in `ls |grep Karma`
do
	mv $build_folder/LICENSE $build_folder/LICENSE.electron.packager
	cp $CURRENT/../LICENSE.txt $build_folder/
done
if [ "$1" == "--archive" ]
then
  for i in `ls |grep 'Karma-*'`
  do
    zip -r $i $i
  done
fi
